//
//  HZAreaPickerView.m
//  areapicker
//
//  Created by Cloud Dai on 12-9-9.
//  Copyright (c) 2012年 clouddai.com. All rights reserved.
//

#import "HZAreaPickerView.h"
#import <QuartzCore/QuartzCore.h>
#import "FMDatabase.h"

#define kDuration 0.3

@interface HZAreaPickerView ()
{
    NSMutableArray *provinces, *cities;
    
    FMDatabase *_dataBase;
    
    NSInteger didSelectedFirst;
    NSInteger didSelectedSecond;
    NSString *provincess;
    NSInteger *citysrow;

    
}

@end

@implementation HZAreaPickerView

@synthesize delegate=_delegate;
@synthesize pickerStyle=_pickerStyle;
@synthesize locatePicker = _locatePicker;

- (void)dealloc
{
    [_locatePicker release];
    [provinces release];
    [super dealloc];
}

- (id)initWithStyle:(HZAreaPickerStyle)pickerStyle delegate:(id<HZAreaPickerDelegate>)delegate
{
    
    self = [[[[NSBundle mainBundle] loadNibNamed:@"HZAreaPickerView" owner:self options:nil] objectAtIndex:0] retain];
    if (self) {
        self.delegate = delegate;
        self.pickerStyle = pickerStyle;
        self.locatePicker.dataSource = self;
        self.locatePicker.delegate = self;
        
        provinces = [[NSMutableArray alloc]init];
        cities = [[NSMutableArray alloc]initWithCapacity:30];
        
        
        didSelectedFirst = 0;
        didSelectedSecond = 0;
        
        //加载数据
        if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
            NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"areas" ofType:@"db"];
            _dataBase = [[FMDatabase alloc]initWithPath:dbPath];
            if ([_dataBase open]) {
                NSString *sql = [NSString stringWithFormat:@"SELECT * FROM province"];
                FMResultSet *resultSet=[_dataBase executeQuery:sql];
                while ([resultSet next]) {
                    HZLocation *model = [[HZLocation alloc]init];
                    model.cityName = [resultSet stringForColumn:@"name"];
                    model.cityID = [[resultSet stringForColumn:@"id"] integerValue];
                    [provinces addObject:model];
                }
                [_dataBase close];
            }
            else{
                MyNSLog("打开数据库失败!");
            }
            
            
            
            if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
                [cities addObjectsFromArray:[self getCityArray:0]];
            }
        } else{

        }
    }
        
    return self;
    
}


- (NSArray *)getCityArray:(NSInteger)provinceRow{
    NSMutableArray *array = [NSMutableArray array];
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"areas" ofType:@"db"];
        _dataBase = [[FMDatabase alloc]initWithPath:dbPath];
        if ([_dataBase open]) {
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM city where province_id = '%@'",[NSString stringWithFormat:@"%ld",provinceRow + 1]];
            FMResultSet *resultSet=[_dataBase executeQuery:sql];
            while ([resultSet next]) {
                HZLocation *model = [[HZLocation alloc]init];
                model.cityName = [resultSet stringForColumn:@"name"];
                model.cityID = [[resultSet stringForColumn:@"id"] integerValue];
                [array addObject:model];
            }
            
            [_dataBase close];
        }
        else{
            MyNSLog("打开数据库失败!");
        }
    }
    return array;
}




#pragma mark - PickerView lifecycle

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        return 2;
    } else{
        return 2;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return [provinces count];
            break;
        case 1:
            return [cities count];
            break;

        default:
            return 0;
            break;
    }
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = nil;
    label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 90, 20)];
    label.font = [UIFont boldSystemFontOfSize:17.f];
    
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = NSTextAlignmentCenter;
    switch (component) {
        case 0:
          
            label.text = [NSString stringWithFormat:@"%@",((HZLocation *)[provinces objectAtIndex:row ]).cityName];
            provincess = label.text;

            break;
            
        case 1:
            @try {
                if ([provincess isEqualToString:@"香港"] || [provincess isEqualToString:@"澳门"] || [provincess isEqualToString:@"台湾"]) {
                label.text = @"";
                }else{
                    label.text = [NSString stringWithFormat:@"%@", ((HZLocation *)[cities objectAtIndex:row ]).cityName];
                }
            }
            @catch (NSException *exception) {
//                NSLog(@"%@",exception);
            }

            break;
    }
    return label;
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
        return 90.f;
}


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        switch (component) {
            case 0:
                return ((HZLocation *)[provinces objectAtIndex:row]).cityName;
                
                break;
            case 1:
                return ((HZLocation *)[cities objectAtIndex:row]).cityName;
                
                break;
            
            default:
                return  @"";
                break;
        }
    } else{

    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        switch (component) {
            case 0:
                [cities removeAllObjects];
                [cities addObjectsFromArray:[self getCityArray:row]];
                [self.locatePicker reloadComponent:1];
                [self.locatePicker selectRow:0 inComponent:1 animated:YES];
                didSelectedFirst = row;
                didSelectedSecond = 0;
                break;
            case 1:
                didSelectedSecond = row;
                break;
            
            default:
                break;
        }
    } else{

    }
    if([self.delegate respondsToSelector:@selector(pickerDidChangeFirst:andSecond:)]) {
        if (cities.count == 0) {
            [self.delegate pickerDidChangeFirst:[provinces objectAtIndex:didSelectedFirst] andSecond:nil];
        }else{
            @try {
                [self.delegate pickerDidChangeFirst:[provinces objectAtIndex:didSelectedFirst] andSecond:[cities objectAtIndex:didSelectedSecond]];

            }
            @catch (NSException *exception) {
                NSLog(@"%@",exception);
            }
          
        }
        
    }

}



#pragma mark - animation

- (void)showInView:(UIView *) view
{
//    self.frame = CGRectMake(0, view.frame.size.height, self.frame.size.width, self.frame.size.height);
    self.frame = CGRectMake(0, view.frame.size.height, self.frame.size.width, self.frame.size.height);
    [view addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = CGRectMake(0, view.frame.size.height - self.frame.size.height, self.frame.size.width, self.frame.size.height);
    }];
    
}

- (void)cancelPicker
{
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(0, self.frame.origin.y+self.frame.size.height, self.frame.size.width, self.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         [self removeFromSuperview];
                         
                     }];
    
}

@end
